import numpy as np
import matplotlib.pyplot as plt
import sympy as sp

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

# 定义符号变量
x = sp.Symbol('x')

# 分析分段函数在x->1处的单侧极限
def piecewise_function(x_val):
    if x_val < 1:
        return x_val + 1
    else:
        return 2 * x_val

# 计算左右极限
left_limit = sp.limit(x + 1, x, 1, dir='-')
right_limit = sp.limit(2*x, x, 1, dir='+')

print(f"左极限: {left_limit}")
print(f"右极限: {right_limit}")
print(f"函数在x=1处的极限存在: {left_limit == right_limit}")

# 可视化
x_vals_left = np.linspace(0, 0.999, 100)
x_vals_right = np.linspace(1.001, 2, 100)
y_vals_left = [piecewise_function(x) for x in x_vals_left]
y_vals_right = [piecewise_function(x) for x in x_vals_right]

plt.figure(figsize=(10, 6))
plt.plot(x_vals_left, y_vals_left, 'b-', linewidth=2, label='左分支: x+1')
plt.plot(x_vals_right, y_vals_right, 'g-', linewidth=2, label='右分支: 2x')
plt.axvline(x=1, color='r', linestyle='--', alpha=0.7, label='x=1')
plt.plot(1, 2, 'ro', markersize=8)
plt.plot(1, 2, 'go', markersize=8)
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('分段函数在x=1处的单侧极限')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()